package message

import (
	"bytes"
	"encoding/binary"
	"gitee.com/zhongguo168a/gocodes/datax/binaryx"
	"gitee.com/zhongguo168a/gocodes/myx/errorx"
	"io"
)

// 服务器推送消息
type PushMessage struct {
	// 0-json 1-byte
	SerializeMode int8
	//
	Data []byte //消息的内容
}

func (msg *PushMessage) Unpack(reader io.Reader, maxPacketSize int) (err error) {
	msg.Data, err = binaryx.ReadBytes(reader, binary.LittleEndian)
	if err != nil {
		err = errorx.Wrap(err, "read data")
		return
	}
	//判断dataLen的长度是否超出我们允许的最大包长度
	if maxPacketSize > 0 && len(msg.Data) > maxPacketSize {
		err = errorx.New("too large msg data received")
		return
	}
	return
}

//封包方法(压缩数据)
func (msg *PushMessage) Pack() ([]byte, error) {
	//创建一个存放bytes字节的缓冲
	dataBuff := bytes.NewBuffer([]byte{})
	// tag data
	if err := binary.Write(dataBuff, binary.LittleEndian, int8(PushTag_Push)); err != nil {
		return nil, err
	}
	binaryx.WriteUTF(dataBuff, binary.LittleEndian, string(msg.Data))
	return dataBuff.Bytes(), nil
}
